import { useEffect, useRef, useState } from 'react';
import { Document, Page } from 'react-pdf';
import { readBinary } from "@linksaas-git/widget";

function App() {
  const [numPages, setNumPages] = useState<number>();
  const [pdfData, setPdfData] = useState<string | null>(null);

  const divRef = useRef<HTMLDivElement>(null);

  function onDocumentLoadSuccess({ numPages }: { numPages: number }): void {
    setNumPages(numPages);
  }


  useEffect(() => {
    readBinary().then(data => {
      const chunk = 8 * 1024;
      const dataStrList = [] as string[];
      for (let i = 0; i < data.length / chunk; i++) {
        const buf = data.slice(i * chunk, (i + 1) * chunk);
        dataStrList.push(String.fromCharCode(...buf));
      }
      const dataB64 = btoa(dataStrList.join(""));
      setPdfData(`data:application/pdf;base64,${dataB64}`);
    });
  }, []);

  return (
    <div ref={divRef}>
      {pdfData != null && divRef.current != null && (
        <Document file={pdfData} onLoadSuccess={onDocumentLoadSuccess}>
          {Array.from(new Array(numPages), (_el, index) => (
            <Page
              key={`page_${index + 1}`}
              pageNumber={index + 1}
              width={(divRef.current?.clientWidth ?? 100) - 30}
            />
          ))}
        </Document>
      )}

    </div>
  )
}

export default App
